import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { Box, Skeleton } from '@chakra-ui/react';
import MyIcon from '@fastgpt/web/components/common/Icon';

const EChartsCodeBlock = ({ code }: { code: string }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const eChart = useRef<ECharts>();
  const [option, setOption] = useState<any>();
  const [width, setWidth] = useState(400);

  useEffect(() => {
    const clientWidth = document.getElementById('chat-container')?.clientWidth || 500;
    setWidth(clientWidth * 0.9);
    setTimeout(() => {
      eChart.current?.resize();
    }, 100);
  }, []);

  useEffect(() => {
    let option;
    //   const markdown = `
    //   {
    //     "title": {
    //       "text": "Echarts 示例"
    //     },
    //     "xAxis": {
    //       "type": "category",
    //       "data": ["A", "B", "C", "D", "E"]
    //     },
    //     "yAxis": {
    //       "type": "value"
    //     },
    //     "series": [{
    //       "data": [10, 20, 30, 40, 50],
    //       "type": "bar"
    //     }]
    //   }
    // `;
    try {
      console.log('chartdata=====================', code);
      option = JSON.parse(code.trim());
      // option = JSON.parse(markdown.trim());
      option = {
        ...option,
        toolbox: {
          show: false,
          feature: {
            saveAsImage: {}
          }
        }
      };
      setOption(option);
    } catch (error) {}

    if (!option) return;

    (async () => {
      // @ts-ignore
      await import('echarts-gl');
    })();

    if (chartRef.current) {
      eChart.current = echarts.init(chartRef.current);
      eChart.current.setOption(option);
      eChart.current?.resize();
    }

    return () => {
      if (eChart.current) {
        eChart.current.dispose();
      }
    };
  }, [code]);

  return (
    <Box overflowX={'auto'}>
      <MyIcon
        name={'support/outlink/share'}
        w={'14px'}
        color={'primary.600'}
        position={'absolute'}
        right={7}
        top={4}
        cursor={'pointer'}
        onClick={() => {
          window.parent.postMessage({ id: option.id }, '*');
        }}
      />
      <Box h={'400px'} minW={'100px'} w={`${width}px`} ref={chartRef} />
      {!option && <Skeleton isLoaded={true} fadeDuration={2} h={'400px'} w={`400px`}></Skeleton>}
    </Box>
  );
};

export default EChartsCodeBlock;
